const path = require("path");
const webpack = require('webpack')
// 单独打包 css
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
// 压缩 index.html, 并自动引入打包文件
const HtmlWebpackPlugin = require("html-webpack-plugin");
// 独立出 ts 类型检查的进程，加快编译速度
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
// 美化终端构建时的进度条样式
const webpackBar = require("webpackbar");
// Eslint 代码检测
const ESLintPlugin = require("eslint-webpack-plugin");

// 加载ENV变量到项目内，可以使用 process.env.* 获取
const envConfig = process.env.CONFIG_ENV
const dotenv = require("dotenv");
const DotenvPlugin = require("dotenv-webpack");
const envPath = path.resolve(__dirname, `../${envConfig}`);
dotenv.config({
  path: envPath,
});

const { version, title } = require("../package.json");
const { srcPath, publicPath, buildPath, iconPath } = require("./path");
const isDev = process.env.NODE_ENV === 'development'
console.log('isDev--->', isDev)
const webpackBaseConfig = {
  entry: [`${srcPath}/main.tsx`],
  output: {
    path: buildPath,
    filename: "js/[name].bundle.js",
    // 打包后的public path，即基础路径
    publicPath: "/",
  },
  resolve: {
    alias: {
      "@": srcPath,
    },
    extensions: [".tsx", ".ts", ".js"],
  },
  module: {
    rules: [
      {
        // ts js 解析
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: "babel-loader",
          },
        ],
      },
      {
        // .css 解析
        test: /\.css$/,
        use: [
          // style-loader 与 MiniCssExtractPlugin 不能同时使用。MiniCssExtractPlugin 在生产模式使用
          isDev ? "style-loader" : MiniCssExtractPlugin.loader, 
          "css-loader", 
          "postcss-loader"
        ],
      },
      {
        // .less 解析
        test: /\.less$/,
        use: [
          isDev ? "style-loader" : MiniCssExtractPlugin.loader,
          "css-loader",
          "postcss-loader",
          {
            loader: "less-loader",
            options: {
              lessOptions: {
                javascriptEnabled: true,
              },
            },
          },
          // 在这里引入要增加的全局less文件
          {
            loader: "style-resources-loader",
            options: {
              patterns: path.resolve(srcPath, "./styles/var.less"),
            },
          },
        ],
      },
      {
        // svg 图标解析
        test: /\.svg$/,
        include: [iconPath],
        use: [
          {
            loader: "babel-loader",
          },
          {
            loader: "@svgr/webpack",
            options: {
              babel: false,
              icon: true,
              svgo: false,
            },
          },
        ],
      },
      {
        // 文件解析
        test: /\.(eot|woff|otf|svg|ttf|woff2|appcache|mp3|mp4|pdf)$/i,
        include: [srcPath],
        exclude: [iconPath],
        // 使用 webpack5 的资源处理
        type: 'asset/resource',
        generator: {
          filename: 'static/[hash][ext][query]'
        }
      },
      {
        // 图片解析
        test: /\.(png|jpg|jpeg|gif)$/i,
        // 解决 webpack5 自带的资源处理 冲突问题
        type: 'javascript/auto',
        use: [
          {
            loader: "url-loader",
            options: {
              esModule:false,
              limit: 9000,
              name: "assets/[name]-[hash:4].[ext]",
            },
          },
        ],
      },
      {
        // wasm文件解析
        test: /\.wasm$/,
        include: path.resolve(__dirname, "src"),
        type: "webassembly/experimental",
      },
      {
        // xml文件解析
        test: /\.xml$/,
        include: path.resolve(__dirname, "src"),
        use: ["xml-loader"],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "css/[name].[chunkhash:8].css", // 生成的文件名
      ignoreOrder: true, // 忽略因CSS文件引入顺序不一致而抛出的警告信息，多为antd内部css引起
    }),
    new ESLintPlugin({
      // 排除node_modules文件夹的eslint检查
      exclude: ["node_modules", "webpack"],
      // 自动修复js格式错误
      fix: true,
      // 制定 检测的代码
      extensions: ['.ts', '.tsx'],
      // 只处理 错误，忽略警告
      quiet: true
    }),
    new webpackBar(),
    new HtmlWebpackPlugin({
      // 生成的html存放路径，相对于 output.path
      filename: "index.html",
      // html模板路径
      template: path.resolve(publicPath, "./index.html"),
      // html模板 参数
      templateParameters: {
        title: process.env.PROJECT_NAME || title,
      },
      // 自动把根目录下的favicon.ico图片加入html
      favicon: path.resolve(publicPath, "./favicon.ico"),
      // 是否将js放在body的末尾
      inject: true,
    }),
    new ForkTsCheckerWebpackPlugin(),
    new DotenvPlugin({
      path: envPath,
    }),
    // 编译后的参数设置
    new webpack.DefinePlugin({
      "process.env.VERSION" : JSON.stringify(version)
   })
  ],
};

module.exports = webpackBaseConfig;
